import Taro, { Component, Config } from '@tarojs/taro'
import { Button, Image, ScrollView, Text, View } from '@tarojs/components'
import './index.scss'
import classNames from 'classnames'
import { getPage } from "@/api/productApi"
import moment from '@/assets/js/moment.min'
import { getCustomPage } from "@/api/pageApi"
import { TAB_BAR_HEIGHT } from "@/config/config"
import { toSearchPage } from "@/utils/page_router"
import { toIntegralCheckinPage } from '@/utils/page_router'
import { getScoreConfig, getSignScore } from '@/api/userApi'
import {GoodsFiveList, ListEmpty, Loading, LoadMore, TabBar} from "@/components/index"
import {getBrand} from "@/utils/storage";

const defTabKey = 'recommend'
export default class Index extends Component {
  state: any
  tabNav: any
  config: Config = {
    navigationStyle: 'custom',
    backgroundTextStyle: "dark",
  }

  constructor() {
    super(...arguments)
    this.state = {
      page: 1,
      limit: 10,
      tabKey: defTabKey,
      loading: true,
      signList: [],
      dataList: [],
      signScore: 0,
      scoreInfo: {},
      customList: [],
      loadStatus: 'loading',
    }
  }

  componentDidMount () {
    this.getIndexData()
    this.getGoods()
  }

  componentDidShow() {
    this.getScore()
  }

  //  监听用户上拉触底事件
  onReachBottom(){
    this.getGoods()
  }

  //  获取积分
  async getScore() {
    const config = await getScoreConfig().then(({ data }) => data)
    await getSignScore().then(({ data }) => {
      const current = moment().add(data.currencyDay - 1, 'day')
      const list = config.map((item, key) => ({ ...item, time: current.add(key, 'day').format('MM.DD') }))

      this.setState({
        signList: list,
        scoreInfo: data,
        signScore: list[data.currencyDay]['number']
      })

      setTimeout(() => {
        this.setState({
          loading: false
        })
      }, 800)
    })
  }

  //  获取首页数据
  getIndexData () {
    getCustomPage('integral').then(({ data }) => {

      const list = (data.content || []).map(item => {
        switch (item.key) {
          case 'tabNav':
            this.tabNav = item
            break
        }
        return item
      })
      this.setState({
        customList: list
      })
    })
  }

  //  切换tab
  onSwitchTab(key) {
    this.setState({
      page: 1,
      tabKey: key,
      goodsList: [],
      loadStatus: 'loading'
    }, () => {
      this.getGoods()
    })
  }

  //  分页获取商品
  getGoods() {
    const { page, limit, tabKey, dataList, loadStatus }:any = this.state
    const query = { page, limit }
    if (loadStatus === 'noMore') {
      return
    }

    if (tabKey !== defTabKey) {
      query['categoryId'] = tabKey
    }

    getPage(query).then(res => {
      const { list, totalCount } = res.data
      this.setState({
        page: page + 1,
        dataList: page === 1 ? list : dataList.concat(list),
        loadStatus: (page * limit >= totalCount) ? 'noMore' : 'loading',
      })
    })
  }

  render () {
    const { tabNav } = this
    const { loading, signList, dataList, tabKey, loadStatus, signScore, scoreInfo } = this.state

    return (<View className='index custom-page'>
      {loading && <Loading/>}
      <View className='integral-box'>
        <View className='integral-info f-g-5 f-d-c'>
          <View className='integral-title'>我的{getBrand()}</View>
          <View className='integral-number bnn-number'>{scoreInfo.totalScore}</View>
          <Button className='checkin-btn xf-btn xf-btn-round xf-btn-primary' onClick={() => toIntegralCheckinPage()}>立即签到 + {signScore}</Button>
        </View>

        <View className='menu-list'>
          <View className='menu-item'>查询订单</View>
          <View className='menu-item'>联系客服</View>
          <View className='menu-item'>{getBrand()}规则</View>
        </View>

        <View className='integral-prompt f-g-5'>{getBrand()}可兑换商品，七天后过期清零，请尽快使用</View>
      </View>

      <View className='sign-wrap'>
        <View className='sign-left f-g-5 f-d-c'>
          <View className='sign-title'>已签到</View>
          <View className='sign-day bnn-number'>
            <Text className='sign-day-num'>{scoreInfo.currencyDay}</Text>天
          </View>
        </View>
        <View className='sign-right'>
          <View className='sign-list'>
            {
              signList.map((item, key) => {
                return (
                  <View key={key} className='sign-item bnn-number'>
                    <View className='sign-name'>{item.time}</View>
                    <View className='sign-status'>
                      {
                        key < scoreInfo.currencyDay ? (
                          <View className='sign-circle sign-active bnn-icon'>&#xe645;</View>
                        ) : (
                          <View className='sign-circle'/>
                        )
                      }
                    </View>
                    <View className='sign-integral'>+{item.number}</View>
                  </View>
                )
              })
            }
            <View className='sign-line'/>
          </View>
        </View>
      </View>

      {tabNav && <View className='tab-nav'>
        <View className={classNames('tab-nav__left tab-nav__cty-item', {['tab-nav__cty-active']: tabKey === defTabKey})} onClick={this.onSwitchTab.bind(this, defTabKey)}>
          <Text className='tab-nav__cty-text'>精选</Text>
        </View>
        {/*// @ts-ignore*/}
        <ScrollView scrollX enhanced showScrollbar={false} className='tab-nav__cty-scroll'>
          <View className='tab-nav__cty-list'>
            {tabNav.list.map(cty => {
              return (<View key={cty.id} className={classNames('tab-nav__cty-item', {['tab-nav__cty-active']: tabKey === cty.id})} onClick={this.onSwitchTab.bind(this, cty.id)}>
                {cty.img ? (
                  <Image src={cty.img} mode='heightFix' className='tab-nav__cty-img'/>
                ) : (
                  <Text className='tab-nav__cty-text'>{cty.name}</Text>
                )}
              </View>)
            })}
          </View>
        </ScrollView>
        <View className='tab-nav__right' onClick={() => toSearchPage()}>全部</View>
      </View>}

      <GoodsFiveList list={dataList}/>

      {!dataList.length && loadStatus == 'noMore' ? (<ListEmpty className='list-empty'/>) : (<LoadMore status={loadStatus}/>)}

      <View style={{height: `${TAB_BAR_HEIGHT}px`}}/>
      <TabBar />
    </View>)
  }
}
